package com.autoglm.ui.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.autoglm.data.model.Task
import com.autoglm.data.model.TaskStatus
import com.autoglm.data.repository.GLMRepository
import com.autoglm.data.repository.TaskRepository
import com.autoglm.data.repository.UserPreferenceRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 主屏幕ViewModel
 * 管理主屏幕的状态和业务逻辑
 */
@HiltViewModel
class MainViewModel @Inject constructor(
    private val glmRepository: GLMRepository,
    private val taskRepository: TaskRepository,
    private val userPreferenceRepository: UserPreferenceRepository
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(MainUiState())
    val uiState: StateFlow<MainUiState> = _uiState.asStateFlow()
    
    init {
        loadRecentTasks()
    }
    
    /**
     * 加载最近任务
     */
    private fun loadRecentTasks() {
        viewModelScope.launch {
            taskRepository.getTasksByStatuses(
                listOf(TaskStatus.COMPLETED, TaskStatus.FAILED)
            ).collect { tasks ->
                _uiState.update { it.copy(recentTasks = tasks.take(5)) }
            }
        }
    }
    
    /**
     * 虚拟助手点击事件
     */
    fun onAssistantClick() {
        // TODO: 实现虚拟助手交互
    }
    
    /**
     * 语音按钮点击事件
     */
    fun onVoiceButtonClick() {
        if (_uiState.value.isListening) {
            stopListening()
        } else {
            startListening()
        }
    }
    
    /**
     * 开始语音识别
     */
    private fun startListening() {
        _uiState.update { it.copy(isListening = true) }
        
        // TODO: 实现语音识别
        viewModelScope.launch {
            // 模拟语音识别过程
            kotlinx.coroutines.delay(2000)
            processUserInput("打开高德地图并在三里屯切成3D地图截一张图")
        }
    }
    
    /**
     * 停止语音识别
     */
    private fun stopListening() {
        _uiState.update { it.copy(isListening = false) }
    }
    
    /**
     * 处理用户输入
     */
    private fun processUserInput(userInput: String) {
        _uiState.update { 
            it.copy(
                isListening = false,
                isProcessing = true,
                currentInput = userInput
            ) 
        }
        
        viewModelScope.launch {
            try {
                // 理解用户指令
                val intentResult = glmRepository.understandUserIntent(userInput)
                intentResult.fold(
                    onSuccess = { intent ->
                        // 规划任务步骤
                        val planningResult = glmRepository.planTaskSteps(userInput, "高德地图")
                        planningResult.fold(
                            onSuccess = { plan ->
                                // 创建任务
                                createAndExecuteTask(userInput, plan)
                            },
                            onFailure = { error ->
                                _uiState.update { 
                                    it.copy(
                                        isProcessing = false,
                                        errorMessage = "任务规划失败: ${error.message}"
                                    ) 
                                }
                            }
                        )
                    },
                    onFailure = { error ->
                        _uiState.update { 
                            it.copy(
                                isProcessing = false,
                                errorMessage = "指令理解失败: ${error.message}"
                            ) 
                        }
                    }
                )
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(
                        isProcessing = false,
                        errorMessage = "处理失败: ${e.message}"
                    ) 
                }
            }
        }
    }
    
    /**
     * 创建并执行任务
     */
    private suspend fun createAndExecuteTask(userInput: String, plan: String) {
        try {
            // 创建任务
            val task = taskRepository.createTask(
                description = "高德地图3D截图",
                userInput = userInput,
                steps = emptyList(), // TODO: 解析plan生成步骤
                parameters = mapOf("location" to "三里屯")
            )
            
            _uiState.update { 
                it.copy(
                    isProcessing = false,
                    currentTask = task
                ) 
            }
            
            // 执行任务
            executeTask(task)
            
        } catch (e: Exception) {
            _uiState.update { 
                it.copy(
                    isProcessing = false,
                    errorMessage = "任务创建失败: ${e.message}"
                ) 
            }
        }
    }
    
    /**
     * 执行任务
     */
    private fun executeTask(task: Task) {
        viewModelScope.launch {
            try {
                // TODO: 实现任务执行逻辑
                // 这里应该调用TaskExecutionService
                
                // 模拟任务执行
                kotlinx.coroutines.delay(5000)
                
                // 更新任务状态
                taskRepository.updateTaskStatus(task.id, TaskStatus.COMPLETED)
                
                _uiState.update { 
                    it.copy(
                        currentTask = null,
                        errorMessage = null
                    ) 
                }
                
            } catch (e: Exception) {
                taskRepository.updateTaskStatus(task.id, TaskStatus.FAILED, e.message)
                _uiState.update { 
                    it.copy(
                        currentTask = null,
                        errorMessage = "任务执行失败: ${e.message}"
                    ) 
                }
            }
        }
    }
    
    /**
     * 任务点击事件
     */
    fun onTaskClick(taskId: String) {
        // TODO: 实现任务详情查看
    }
    
    /**
     * 清除错误消息
     */
    fun clearError() {
        _uiState.update { it.copy(errorMessage = null) }
    }
}

/**
 * 主屏幕UI状态
 */
data class MainUiState(
    val isListening: Boolean = false,
    val isProcessing: Boolean = false,
    val currentInput: String? = null,
    val currentTask: Task? = null,
    val recentTasks: List<Task> = emptyList(),
    val errorMessage: String? = null
)
